package edu.washington.cs.workflow.analysis.guistructure.uievents;

import javax.swing.text.JTextComponent;

import org.uispec4j.Panel;
import org.uispec4j.TextBox;
import org.uispec4j.Trigger;
import org.uispec4j.UIComponent;

import edu.washington.cs.workflow.analysis.guistructure.Spec4JUtils;
import edu.washington.cs.workflow.analysis.guistructure.uievents.UIEvent.WINDOW;
import edu.washington.cs.workflow.util.Utils;

public class TextComponentEvent extends AbstractUIEvent  {

	public final TextBox textComp;
	public final UIAction action;
	public final String inputText;
	
	static int maxlength = 10;
	
	public TextComponentEvent(TextBox textComp, Panel p, UIAction action) {
//		this(textComp, p, action, Utils.nextRandomString(maxlength));
		this(textComp, p, action, Utils.nextRandomString(maxlength));
	}
	
	public TextComponentEvent(TextBox textComp, Panel p, UIAction action, String inputText) {
		Utils.checkNotNull(textComp);
		Utils.checkNotNull(action);
		Utils.checkNotNull(p);
		Utils.checkTrue(textComp.getAwtComponent() instanceof JTextComponent);
		Utils.checkTrue(action.equals(UIAction.SetText), "Invalid action: " + action);
		this.textComp = textComp;
		super.setCurrentPanel(p);
		this.action = action;
		if(inputText != null) {
		    this.inputText = inputText;
		} else {
			this.inputText = "";
		}
	}
	
	@Override
	public UIComponent getUIComponent() {
		return this.textComp;
	}

	@Override
	public UIAction getAction() {
		return this.action;
	}
	
	@Override
	protected WINDOW probeWindowInfoInternal() {
		//XXX suppose no window
		return WINDOW.NONE;
	}

	@Override
	public boolean canFireEvent() {
		return this.textComp.isEnabled().isTrue() && this.textComp.isEditable().isTrue();
	}
	
	@Override
	protected UIEventOutcome fireEventInternal() {
		
		UIEventOutcome outcome = new UIEventOutcome();
		//suppose there is no window pops up XXX
		if(this.textComp.isEditable().isTrue()) {
			try {
			    this.textComp.setText(this.inputText);
			} catch (Throwable e) {
				outcome.setError(e);
			}
			outcome.currentPanelClosed(super.isCurrentPanelClosed()); //NOT needed, I think
			return outcome;
		} else {
		    return null; //if this is not editable, no outcome, since this is illegal!
		}
	}
	
	@Override
	public String toString() {
		return "Set text: " + this.inputText + " to " + this.getUIComponent().getAwtComponent().getClass() + " : " + this.textComp.getName();
	}

	@Override
	public String getDescription() {
		return "Set text to " + this.getUIComponent().getAwtComponent().getClass() + " : " + this.textComp.getName();
	}
}
